package com.example.demo;

import jakarta.annotation.PostConstruct;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class RocketMQProducer {

    private static final Logger log = LoggerFactory.getLogger(RocketMQProducer.class);

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() throws Exception {
        producer = new DefaultMQProducer("test-producer-group");
        producer.setNamesrvAddr("192.168.10.32:9876");
        producer.start();
        log.info("RocketMQ 生产者已启动");
    }

    public void sendMessage(String topic, String messageText) throws Exception {
        Message message = new Message(topic, messageText.getBytes());
        SendResult result = producer.send(message);
        log.info("发送消息: {}, 结果: {}", messageText, result);
    }
}
